package cn.mumzone.pos.ui.fragment;

import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.adapter.TextWatcherAdapter;
import cn.mumzone.basic.adapter.rv.MultiItemTypeAdapter;
import cn.mumzone.basic.base.BaseFragment;
import cn.mumzone.basic.dialog.AlertDialog;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.EditTextUtil;
import cn.mumzone.basic.util.ItemClickSupport;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.NetUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.RxBus;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.R;
import cn.mumzone.pos.dialog.PosDialog;
import cn.mumzone.pos.event.MoreViewChangeEvent;
import cn.mumzone.pos.model.GoodsTreeEntity;
import cn.mumzone.pos.model.RepoGoodsEntity;
import cn.mumzone.pos.model.RepoGoodsSpecEntity;
import cn.mumzone.pos.model.RepoListGoodsEntity;
import cn.mumzone.pos.model.RepositoryEntity;
import cn.mumzone.pos.presenter.StockSearchPresenter;
import cn.mumzone.pos.presenter.contract.StockSearchContract;
import cn.mumzone.pos.ui.adapter.ADA_RepoGoods;
import cn.mumzone.pos.ui.adapter.ADA_SelectRepository;
import cn.mumzone.pos.ui.widgets.GoodsClassifyView;
import cn.mumzone.pos.ui.widgets.refresh.SmartRefreshLayout;
import cn.mumzone.pos.ui.widgets.refresh.api.RefreshLayout;
import cn.mumzone.pos.ui.widgets.refresh.listener.OnRefreshListener;
import cn.mumzone.pos.ui.widgets.util.StringSpanUtils;
import cn.mumzone.pos.util.GoodsUtil;

/**
 * Created by qiuzhenhuan on 2019/7/30.
 */

public class FRA_StockSearch extends BaseFragment<StockSearchPresenter> implements StockSearchContract.View {

    @BindView(R.id.tv_repository)
    TextView tvRepository;
    @BindView(R.id.tv_good_type)
    TextView tvGoodType;
    @BindView(R.id.et_scan)
    EditText etScan;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.iv_clear_input)
    ImageView ivClearInput;
    @BindView(R.id.rb_search)
    RadioButton rbSearch;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.rv_repo_goods)
    LRecyclerView rvRepoGoods;
    @BindView(R.id.rl_repository)
    RelativeLayout rlRepository;
    @BindView(R.id.rl_good_type)
    RelativeLayout rlGoodType;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;
    @BindView(R.id.ll_goods)
    LinearLayout llGoods;
    @BindView(R.id.tv_good_name)
    TextView tvGoodsName;
    @BindView(R.id.tv_good_spec)
    TextView tvGoodsSpec;
    @BindView(R.id.tv_good_num)
    TextView tvGoodsNum;
    @BindView(R.id.ll_batch_goods)
    LinearLayout llBatchGoods;
    @BindView(R.id.rl_not_batch_goods)
    RelativeLayout rlNotBatchGoods;
    @BindView(R.id.ll_goods_detail)
    LinearLayout llGoodsDetail;


    private ADA_RepoGoods mGoodsAdapter;
    private LRecyclerViewAdapter mGoodsViewAdapter;

    private AlertDialog mSelectRepoDialog;
    private ADA_SelectRepository mRepoAdapter;

    private AlertDialog mSelectGoodsClassifyDialog;
    private GoodsClassifyView goodsClassifyView;

    private AlertDialog mScanGoodsDialog;
    private ADA_RepoGoods mScanGoodsAdapter;


    private RepositoryEntity mSelectedRepo;
    private GoodsTreeEntity mSelectedGoodsClassify;
    private boolean isScanExecuted = false;

    @Override
    protected void onUserVisible() {
        mPresenter.loadRepositoryList();
        mPresenter.loadGoodsTreeClassify();
        etScan.requestFocus();
    }

    @Override
    protected void initEventAndData() {

        initViews();

        initSelectRepoDialog();

        initSelectGoodsClassifyDialog();

        initScanGoodsDialog();

        mPresenter.loadRepositoryList();
        mPresenter.loadGoodsTreeClassify();
        mPresenter.initEvent();
    }


    private void initViews() {

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                String keyword = etSearch.getText().toString().trim();
                mPresenter.loadRepoGoodsById(mSelectedRepo != null ? StringUtils.get(mSelectedRepo.getId()) : "",
                        mSelectedGoodsClassify != null ? StringUtils.get(mSelectedGoodsClassify.getValue()) : "",
                        keyword, true, false);
                rvRepoGoods.setNoMore(false);
            }
        });

        rvRepoGoods.setLayoutManager(new LinearLayoutManager(mContext));
        mGoodsAdapter = new ADA_RepoGoods(mContext);
        mGoodsViewAdapter = new LRecyclerViewAdapter(mGoodsAdapter);
        rvRepoGoods.setAdapter(mGoodsViewAdapter);
        rvRepoGoods.setPullRefreshEnabled(false);
        rvRepoGoods.setLoadMoreEnabled(true);
        rvRepoGoods.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                String keyword = etSearch.getText().toString().trim();
                mPresenter.loadRepoGoodsById(mSelectedRepo != null ? StringUtils.get(mSelectedRepo.getId()) : "",
                        mSelectedGoodsClassify != null ? StringUtils.get(mSelectedGoodsClassify.getValue()) : "",
                        keyword, false, false);
            }
        });

        mGoodsAdapter.setOnItemClickListener(new ADA_RepoGoods.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                showGoodsItem(mGoodsAdapter.getDataList().get(position - 1));
            }
        });

        etScan.setInputType(InputType.TYPE_NULL);
        EditTextUtil.hideSoftInputMethod(mContext, etScan);
        GoodsUtil.initScanForGoodsSold(mContext, etScan, etSearch, new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String code = v.getText().toString().trim();
                if (actionId == KeyEvent.ACTION_DOWN && !TextUtils.isEmpty(code)) {

                    if (!NetUtil.isNetworkAvailable(mContext)) {
                        PosToast.INSTANCE.makeShortToast(mContext, "网络不给力，请稍候再试");
                        return true;
                    }

                    if (!isScanExecuted) {
                        mPresenter.loadRepoGoodsById(mSelectedRepo != null ? StringUtils.get(mSelectedRepo.getId()) : "",
                                "", code, true, true);
                        rvRepoGoods.setNoMore(false);
                    }
                    isScanExecuted = true;
                    etScan.setText("");
                }
                return true;
            }
        }, new TextWatcherAdapter() {
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                boolean isInputNotEmpty = !TextUtils.isEmpty(etSearch.getText().toString());
                ivClearInput.setVisibility(isInputNotEmpty ? View.VISIBLE : View.GONE);
                rbSearch.setEnabled(isInputNotEmpty);
                rbSearch.setChecked(isInputNotEmpty);
            }
        });

        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    EditTextUtil.hideSoftInput(mContext, v);
                    refreshLayout.autoRefresh();
                    etScan.requestFocus();
                }
                return false;
            }
        });
    }


    private void initSelectRepoDialog() {

        mSelectRepoDialog = new PosDialog.PosBuilder(mContext, PosDialog.DIALOG_BLACK_TITLE)
                .setRealDialogContent(R.layout.dialog_select_repotory)
                .setUseRadiusBg(false)
                .setDialogTitle("选择仓库")
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .fromRight(true)
                .create();
        RecyclerView rvRepository = mSelectRepoDialog.getView(R.id.rv_repository);
        rvRepository.setLayoutManager(new LinearLayoutManager(mContext));
        mRepoAdapter = new ADA_SelectRepository(mContext);
        mRepoAdapter.setOnItemClickedListener(new ADA_SelectRepository.OnItemClickedListener() {
            @Override
            public void onItemClicked(int position) {
                mSelectedRepo = mRepoAdapter.getDataList().get(position);
                tvRepository.setText(mSelectedRepo.getRepositoryName());
                closeDialog(mSelectRepoDialog);
                refreshLayout.autoRefresh();
            }
        });
        rvRepository.setAdapter(mRepoAdapter);
        rvRepository.setHasFixedSize(true);
        mSelectRepoDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                etScan.requestFocus();
            }
        });
    }

    private void initSelectGoodsClassifyDialog() {
        mSelectGoodsClassifyDialog = new PosDialog.PosBuilder(mContext, PosDialog.DIALOG_BLACK_TITLE)
                .setRealDialogContent(R.layout.dialog_select_goods_classify)
                .setUseRadiusBg(false)
                .setDialogTitle("选择商品分类")
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .fromRight(true)
                .create();
        goodsClassifyView = mSelectGoodsClassifyDialog.getView(R.id.view_goods_classify);
        goodsClassifyView.setDoubleCheck(false);
        goodsClassifyView.setOnGoodsClassifyClickListener(new GoodsClassifyView.OnGoodsClassifyClickListener() {
            @Override
            public void onGoodsClassifyClick(GoodsTreeEntity goodsTreeEntity) {
                mSelectedGoodsClassify = goodsTreeEntity;
                if (mSelectedGoodsClassify != null) {
                    tvGoodType.setText(StringUtils.get(goodsTreeEntity.getLabel()));
                } else {
                    tvGoodType.setText("全部");
                }
                closeDialog(mSelectGoodsClassifyDialog);
                refreshLayout.autoRefresh();
            }
        });
    }

    private void initScanGoodsDialog() {
        mScanGoodsDialog = new PosDialog.PosBuilder(mContext, PosDialog.DIALOG_BLACK_TITLE)
                .setRealDialogContent(R.layout.dialog_scan_repo_goods)
                .setUseRadiusBg(false)
                .setDialogTitle("扫码查询商品")
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .fromRight(true)
                .create();
        mScanGoodsDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        EditText etCode = mScanGoodsDialog.getView(R.id.et_code);
        etCode.setInputType(InputType.TYPE_NULL);
        EditTextUtil.hideSoftInputMethod(mContext, etCode);
        etCode.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String code = v.getText().toString().trim();
                if (actionId == KeyEvent.ACTION_DOWN && !TextUtils.isEmpty(code)) {

                    if (!NetUtil.isNetworkAvailable(mContext)) {
                        PosToast.INSTANCE.makeShortToast(mContext, "网络不给力，请稍候再试");
                        return true;
                    }

                    if (!isScanExecuted) {
                        mPresenter.loadRepoGoodsById(mSelectedRepo != null ? StringUtils.get(mSelectedRepo.getId()) : "",
                                "", code, true, true);
                    }
                    isScanExecuted = true;
                    v.setText("");
                }
                return true;
            }
        });
        RecyclerView rvGoodsList = mScanGoodsDialog.getView(R.id.rv_goods_list);
        rvGoodsList.setLayoutManager(new LinearLayoutManager(mContext));
        mScanGoodsAdapter = new ADA_RepoGoods(mContext);
        rvGoodsList.setAdapter(mScanGoodsAdapter);
        mScanGoodsDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                etScan.requestFocus();
            }
        });
    }


    @OnClick({R.id.iv_back, R.id.rl_repository, R.id.rl_good_type, R.id.iv_clear_input, R.id.rb_search})
    void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                RxBus.getDefault().post(new MoreViewChangeEvent(MoreViewChangeEvent.MORE_VIE_HOME));
                break;
            case R.id.rl_repository:
                showDialog(mSelectRepoDialog);
                break;
            case R.id.rl_good_type:
                showDialog(mSelectGoodsClassifyDialog);
                break;
            case R.id.iv_clear_input:
                etSearch.setText("");
                refreshLayout.autoRefresh();
                etScan.requestFocus();
                break;
            case R.id.rb_search:
                refreshLayout.autoRefresh();
                etScan.requestFocus();
                break;
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.fra_search_repository;
    }

    @Override
    public void showRepositoryList(List<RepositoryEntity> repositoryList) {
        if (!ListUtil.isListEmpty(repositoryList)) {
            mSelectedRepo = repositoryList.get(0);
            tvRepository.setText(repositoryList.get(0).getRepositoryName());
            mRepoAdapter.update(repositoryList, true);
            refreshLayout.autoRefresh();
        } else {
            toggleShowEmpty(true, R.mipmap.ic_bill_empty, "暂未创建仓库", "");
        }
        refreshLayout.setEnableRefresh(!ListUtil.isListEmpty(repositoryList));
        rlRepository.setClickable(!ListUtil.isListEmpty(repositoryList));
        rlGoodType.setClickable(!ListUtil.isListEmpty(repositoryList));
        llSearch.setClickable(!ListUtil.isListEmpty(repositoryList));
        etSearch.setClickable(!ListUtil.isListEmpty(repositoryList));
    }

    @Override
    public synchronized void showGoodsList(List<RepoListGoodsEntity> goodsEntities, boolean isRefresh) {
        refreshLayout.finishRefresh();
        llGoodsDetail.setVisibility(View.VISIBLE);
        rvRepoGoods.setNoMore(ListUtil.isListEmpty(goodsEntities) && goodsEntities.size() < AppConstants.PAGE_SIZE);
        mGoodsAdapter.update(goodsEntities, isRefresh);
        if (isRefresh) {
            rvRepoGoods.setAdapter(mGoodsViewAdapter);
            if (!ListUtil.isListEmpty(goodsEntities)) {
                showGoodsItem(goodsEntities.get(0));
            }
            mGoodsAdapter.clearSelect();
        } else {
            mGoodsViewAdapter.notifyDataSetChanged();
        }


        if (ListUtil.isListEmpty(mGoodsAdapter.getDataList())) {
            toggleShowEmpty(true, R.mipmap.ic_bill_empty, "未搜索到商品", "");
        } else {
            toggleShowEmpty(false);
        }
    }

    private void showGoodsItem(RepoListGoodsEntity repoGoodsEntity) {
        tvGoodsName.setText(StringUtils.get(repoGoodsEntity.getGoodsName()));
        tvGoodsSpec.setText(getFormatGoodsSpec(repoGoodsEntity.getParameter()));
        llBatchGoods.removeAllViews();
        if (!ListUtil.isListEmpty(repoGoodsEntity.getGoodsBatch()) &&
                !StringUtils.isEmpty(repoGoodsEntity.getGoodsBatch().get(0).getGoodsBatchNumber())) {
            rlNotBatchGoods.setVisibility(View.GONE);

            for (RepoGoodsEntity entity : repoGoodsEntity.getGoodsBatch()) {
                View batchView = LayoutInflater.from(mContext).inflate(R.layout.item_goods_batch_stock, llBatchGoods, false);
                TextView tvProductionDate = batchView.findViewById(R.id.tv_production_date);
                TextView tvBatch = batchView.findViewById(R.id.tv_batch);
                TextView tvStockCount = batchView.findViewById(R.id.tv_stock_count);
                if (!StringUtils.isEmpty(entity.getDateInProduced())) {
                    tvProductionDate.setText(
                            AppDateUtil.getDateToString(Long.valueOf(StringUtils.get(entity.getDateInProduced())), AppDateUtil.YYYY_MM_DD1));
                } else {
                    tvProductionDate.setText("");
                }
                tvBatch.setText(StringUtils.get(entity.getGoodsBatchNumber()));
                tvStockCount.setText(String.format("%s%s", StringUtils.get(entity.getGoodsQuantity()), StringUtils.get(entity.getGoodsUnit())));
                llBatchGoods.addView(batchView);
            }
        } else {
            rlNotBatchGoods.setVisibility(View.VISIBLE);
            String goodsQuantity = "0";
            String goodsUnit = "";
            if (!ListUtil.isListEmpty(repoGoodsEntity.getGoodsBatch())) {
                goodsQuantity = repoGoodsEntity.getGoodsBatch().get(0).getGoodsQuantity();
                goodsUnit = repoGoodsEntity.getGoodsBatch().get(0).getGoodsUnit();
            }
            tvGoodsNum.setText(String.format("%s%s", goodsQuantity, goodsUnit));
        }
    }

    private String getFormatGoodsSpec(List<RepoGoodsSpecEntity> goodsSpec) {

        StringBuilder builder = new StringBuilder();
        if (!ListUtil.isListEmpty(goodsSpec)) {
            for (int index = 0; index < goodsSpec.size(); index++) {
                RepoGoodsSpecEntity specBean = goodsSpec.get(index);
                builder.append(specBean.getParamValue());
                if (index < goodsSpec.size() - 1) {
                    builder.append("，");
                }
            }
        }
        return StringSpanUtils.init().addForegroundColorHighLight(mContext.getResources().getColor(R.color.weak_text_color), "规格：")
                .addStr(StringUtils.get(builder.toString(), "无")).build().toString();
    }

    @Override
    public void showScanGoodsDialog(List<RepoListGoodsEntity> list) {
        isScanExecuted = false;

        mScanGoodsAdapter.update(list, true);
        showDialog(mScanGoodsDialog);
    }

    @Override
    protected View getTargetView() {
        return llGoods;
    }

    @Override
    public void showGoodsTreeClassify(List<GoodsTreeEntity> goodsTreeEntities) {
        goodsClassifyView.setData(goodsTreeEntities);
    }

    @Override
    public void showGoBack() {
        etSearch.setText("");
        tvGoodType.setText("全部");
        mSelectedGoodsClassify = null;
        goodsClassifyView.clearSelect();
    }

    @Override
    protected void showNetErrorEmpty() {
        refreshLayout.finishRefresh();
        showNetErrorEmpty(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FRA_StockSearch.super.toggleCloseEmpty();
                refreshLayout.autoRefresh();
            }
        });
    }

    @Override
    public void showError(String msg) {
        if ("无此商品".equals(msg)) {
            toggleShowEmpty(true, R.mipmap.ic_bill_empty, "未搜索到商品", "");
        } else {
            super.showError(msg);
        }
        refreshLayout.finishRefresh();
        rvRepoGoods.refreshComplete(AppConstants.PAGE_SIZE);

        isScanExecuted = false;
    }
}
